package com.situ.crm2026.api;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.crm2026.model.Admin;
import com.situ.crm2026.service.AdminService;
import com.situ.crm2026.service.UploadService;
import com.situ.crm2026.util.JsonResult;
import jakarta.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RequestMapping(value = "/api/v1/admins", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
public class AdminApi {

    private AdminService adminService;
    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @GetMapping
    public ResponseEntity <JsonResult<?>> findAll(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Admin admin){

        Page<Admin> page = new Page<>(pageNo, pageSize);
        page = this.adminService.findAll(page, admin);
        return ResponseEntity.ok(JsonResult.success(page));

    }
    //删除
    @DeleteMapping
    public ResponseEntity <JsonResult<?>> deleteByIds(
            @RequestBody
            @Validated
            @Size(min = 1, message = "要删除的管理员ID至少1个") Integer[] ids) {
    int count = this.adminService.deleteByIds(List.of(ids));

    return ResponseEntity.ok(JsonResult.success(count));
    }

    //新增
    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody @Validated Admin admin) {
    boolean success = this.adminService.save(admin);
    if (success) {
    return ResponseEntity.ok(JsonResult.success(admin));
    }
    return ResponseEntity.ok(JsonResult.fail("保存失败"));
    }

    //修改
    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody @Validated Admin admin) {
    boolean success = this.adminService.update(admin);
    if (success) {
    return ResponseEntity.ok(JsonResult.success(admin));
    }
    return ResponseEntity.ok(JsonResult.fail("修改失败"));
    }
    private UploadService uploadService;
    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }
    //上传头像
    @PostMapping("/avatar")
    public ResponseEntity<JsonResult<?>> uploadAdminAvatar(MultipartFile file) {
        String path = this.uploadService.uploadImage(file, "admin");
        return ResponseEntity.ok(JsonResult.success(path));
    }

}
